package com.ohuang.jiaxiaotong.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bunny.android.library.LoadDataLayout;
import com.ohuang.jiaxiaotong.Activity.ChatActivity;
import com.ohuang.jiaxiaotong.Activity.ClassInfoActivity;
import com.ohuang.jiaxiaotong.Activity.UserMsgActivity;
import com.ohuang.jiaxiaotong.MainActivity;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.EventMsgCode;
import com.ohuang.jiaxiaotong.entity.ChatMsg;
import com.ohuang.jiaxiaotong.entity.ChatMsg2;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;


public class MsgFragment extends Fragment {
    private View view;
    private ListView listView;
    private User user;
    private LoadDataLayout loadDataLayout;
    private CommonAdapter commonAdapter;
    private ArrayList<ChatMsg2> mData;
    private SwipeRefreshLayout swipeRefreshLayout;

    public MsgFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_msg, container, false);
        listView = view.findViewById(R.id.listView_msg);
        loadDataLayout = view.findViewById(R.id.loadData_msg);
        swipeRefreshLayout=view.findViewById(R.id.swipeRefresh_msg);
        if (user != null) {
            loadDataLayout.showLoading("正在努力加载中", new LoadDataLayout.SetImgCallBack() {
                @Override
                public void setImg(ImageView img) {
                    Glide.with(getActivity())
                            .load(R.drawable.gif_loading)
                            .into(img);
                }
            });//显示 load布局 状态正在加载
            HttpGetChatMsg2();
        }
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                HttpGetChatMsg2();
            }
        });


        return view;
    }


    private void HttpGetChatMsg2() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());

        service.getChatMsg2(map).enqueue(new Callback<ArrayList<ChatMsg2>>() {
            @Override
            public void onResponse(Call<ArrayList<ChatMsg2>> call, Response<ArrayList<ChatMsg2>> response) {
                mData = response.body();
                if (mData != null) {
                    if (mData.size() == 0) {
                        loadDataLayout.showEmpty();
                    } else {
                        loadDataLayout.showSuccess();
                    }
                        commonAdapter = new CommonAdapter(getContext(), R.layout.list_chat_item, mData) {
                            @Override
                            protected void convert(ViewHolder viewHolder, Object item, int position) {
                                ChatMsg2 chatMsg2 = (ChatMsg2) item;
                                if (user.getUsername().equals(chatMsg2.getSendName())) {
                                    ImageView imageView = viewHolder.getView(R.id.img_chat_list);
                                    Glide.with(getContext()).load(chatMsg2.getReceiveIcon())
                                            .error(R.drawable.img_icon)
                                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                            .into(imageView);
                                    viewHolder.setText(R.id.txt_username_chat_list
                                            , chatMsg2.getReceiveName());
                                    viewHolder.setText(R.id.txt_content_chat_list,
                                            chatMsg2.getSendName() + ":" + chatMsg2.getContent());
                                } else {
                                    ImageView imageView = viewHolder.getView(R.id.img_chat_list);
                                    Glide.with(getContext()).load(chatMsg2.getSendIcon())
                                            .error(R.drawable.img_icon)
                                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                            .into(imageView);
                                    viewHolder.setText(R.id.txt_username_chat_list
                                            , chatMsg2.getSendName());
                                    viewHolder.setText(R.id.txt_content_chat_list,
                                            chatMsg2.getSendName() + ":" + chatMsg2.getContent());
                                }
                            }
                        };

                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (user.getUsername().equals(mData.get(position).getSendName())) {
                                    Intent intent = new Intent(getContext(), ChatActivity.class);
                                    intent.putExtra("username", mData.get(position).getReceiveName());
                                    startActivity(intent);
                                }else {
                                    Intent intent = new Intent(getContext(), ChatActivity.class);
                                    intent.putExtra("username", mData.get(position).getSendName());
                                    startActivity(intent);
                                }
                            }
                        });
                        listView.setAdapter(commonAdapter);


                } else {
                    loadDataLayout.showError();
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<ArrayList<ChatMsg2>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
                if(commonAdapter==null) {
                    loadDataLayout.showError();
                }else if (commonAdapter.getCount()!=0){
                    Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                }else {
                    loadDataLayout.showError();
                }

            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void GetUserEventBus(EventMsg eventMsg) {
        if (eventMsg.getCode()== EventMsgCode.CODE_6){
            HttpGetChatMsg2();
        }
    }
    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("chat/findInform")
        Call<ArrayList<ChatMsg2>> getChatMsg2(@QueryMap HashMap<String, String> deviceInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
